#include "main.h"

uint8_t gLcdSleepFlag = 0;

/**
 * @brief 显示屏背光熄灭判断
*/
static void lcd_off_judge(void)
{
    if (g_lcd_manager.lcd_off_cnt++ >= LCD_OFF_DELAY)   // 1分钟，将PA3拉低，关闭屏的背光
    {
        g_lcd_manager.lcd_off_cnt = 0;
        if (gpio_output_bit_get(LCDK_CTRL_PORT, LCDK_CTRL_PIN) == SET)
        {
            LCDK_CTRL_DIS;
        }
    }
}

/**
 * @brief 显示屏休眠判断
*/
static void lcd_sleep_judge(void)
{
    if (g_lcd_manager.power_off_cnt++ >= POWER_OFF_DELAY2)  // 静置30min后，关闭背光，停止通讯，只能通过按键唤醒
    {
        g_lcd_manager.power_off_cnt = 0;
        gLcdSleepFlag = 1;
        LCDK_CTRL_DIS;
    }
}

/**
 * @brief 息屏/休眠判断
*/
void sleep_task(void)
{
    static uint8_t chg_cnt = 0, dsg_cnt = 0;

    lcd_off_judge();
    lcd_sleep_judge();

    if (g_lcd_display_info.comm_state == ERR)
    {
        return;
    }
    
    if (ABS(g_lcd_display_info.pack_c) >= 400)   // 电流>=4A 不熄屏、不下电
    {
        g_lcd_manager.power_off_cnt = 0;
        g_lcd_manager.lcd_off_cnt = 0;

        if (gLcdSleepFlag)
        {
            return;
        }
        
        if (g_lcd_display_info.pack_c >= 400)
        {
            if (chg_cnt++ >= 10)
            {
                chg_cnt = 0;
                if (gpio_output_bit_get(LCDK_CTRL_PORT, LCDK_CTRL_PIN) == RESET)
                {
                    LCDK_CTRL_EN;      // 将PA3拉高(熄屏后未休眠时的唤醒操作)
                }
            }
        }
        else if (g_lcd_display_info.pack_c <= -400)
        {
            if (dsg_cnt++ >= 1)
            {
                dsg_cnt = 0;
                if (gpio_output_bit_get(LCDK_CTRL_PORT, LCDK_CTRL_PIN) == RESET)
                {
                    LCDK_CTRL_EN;      // 将PA3拉高(熄灭后未休眠时的唤醒操作)
                }
            }
        }
    }
}

